import os
import subprocess
from tqdm import tqdm
'''参考此文档https://blog.csdn.net/zhengshiougea/article/details/103062720'''
cmds = ["pip list --outdate","pip install --upgrade "]
def update_pip():
    '''升级函数'''
    s1 = cmd_run(cmds[0])
    if len(s1)>2:
        for update_list in tqdm(s1[2:]):
            outdated_pkg = update_list.split(" ",1)[0]
            print(outdated_pkg)
            #执行这个指令,并有返回值
            tmp = cmd_run(cmds[1]+outdated_pkg)
    print(f"升级完成,本次升级库数量为{len(update_list)}")

def cmd_run(directives:str):
    '''在控制台中执行命令,并有返回值,存入到变量r中'''
    cmd = subprocess.Popen(cmds[0],shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    #读取r并自动换行
    r = cmd.stdout.read()
    r = r.decode('gbk').splitlines()
    return r

if __name__ == "__main__":
    update_pip()
